package ui.fragment

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.mynewsapp.databinding.FragmentLoginBinding
import ui.activity.MainActivity


class LoginFragment : Fragment() {
    private lateinit var binding: FragmentLoginBinding

    private lateinit var sharedPreferences: SharedPreferences

    // 设置一个label
    private val PREFS_NAME = "LoginPrefs"
    private val PREFS_IS_LOGGED_IN = "isLoggedIn"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 登录按钮点击事件
        binding.dengluanniu.setOnClickListener {
            val email = binding.editEmailSignIN.text.toString()
            val password = binding.editPassSignIn.text.toString()

            sharedPreferences = requireActivity().getSharedPreferences(
                PREFS_NAME,
                android.content.Context.MODE_PRIVATE
            )
//            val fakeUsers = FakeUserGenerator.generateFakeUsers()
//
//            fakeUsers.forEach { user ->
//                Toast.makeText(
//                    requireActivity(),
//                    "Generated User: ${user.email}, Password: ${user.password}",
//                    Toast.LENGTH_SHORT
//                ).show()
//            }

            saveLoginState(true)
            startActivity(Intent(requireActivity(), MainActivity::class.java))
            requireActivity().finish()


            // TODO: 添加登录逻辑
//            if (email.isNotEmpty() && password.isNotEmpty()) {
//                // 模拟登录成功，跳转到主页面
////                findNavController().navigate(R.id.action_loginFragment_to_mainFragment)
//            } else {
//                // 显示错误提示
//            }
        }

        // 注册链接点击事件
//        binding..setOnClickListener {
//            // 跳转到注册页面
//            findNavController().navigate(R.id.action_loginFragment_to_signUpFragment)
//        }
    }


    // 保存登录的share preference,简单处理
    private fun saveLoginState(isLoggedIn: Boolean) {
        with(sharedPreferences.edit()) {
            putBoolean(PREFS_IS_LOGGED_IN, isLoggedIn)
            apply()
        }
    }
}